package com.linwen.javase.thread;

/**以窗口卖票为例
 * @author : linwen
 * @date : 下午10:27 2021/1/11
 * 实现runnabble接口中用 同步方法
 */
public class 线程锁3 {
    public static void main(String[] args) {
        Window3 window3 = new Window3();
        Thread thread1 = new Thread(window3);
        Thread thread2 = new Thread(window3);
        Thread thread3 = new Thread(window3);
        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
class Window3 implements Runnable{
    private int ticket=100;
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sell();
        }
    }
//将需要同步锁的方法抽象出来，声明为synchronized的，默认当前锁为当前对象this
    private synchronized void sell() {
        if(ticket>0){

            System.out.println(Thread.currentThread().getName() + "==" + ticket);
            ticket--;
        }else{
            System.exit(0);
        }
    }
}
